package perform.database;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import perform.mappings.ClassMappings;
import perform.mappings.ManyToManyMapping;
import perform.type.Type;

public class DatabaseProcessor {
	
	private String name;
	private String createQuery;
	private String useQuery;
	private String dropQuery;
	
	private List<TableProcessor> tables;
	private List<ManyToManyProcessor> manyToManies;
	
	public DatabaseProcessor(Properties properties){
		name = properties.getProperty("name");
		StringBuilder create = new StringBuilder("create database `");
		create.append(name).append("` default character set ").append(properties.get("charset"))
				.append(" collate ").append(properties.get("collation")).append(" ;");
		StringBuilder use = new StringBuilder("use `").append(name).append("` ;");
		StringBuilder drop = new StringBuilder("drop database `").append(name).append("` ;");
		createQuery = create.toString();
		useQuery = use.toString();
		dropQuery = drop.toString();
		tables = new ArrayList<TableProcessor>();
		manyToManies = new ArrayList<ManyToManyProcessor>();
	}
	
	public void generateQueries(List<Class<? extends Type>> classes){
		for(int i = 0; i < classes.size(); i++){
			addTable(new TableProcessor(classes.get(i)));
		}
		Map<String, ManyToManyMapping> m2ms = ClassMappings.getAllManyToManies();
		if(m2ms != null && !m2ms.isEmpty()){
			Iterator<String> names = m2ms.keySet().iterator();
			while(names.hasNext()){
				addManyToMany(new ManyToManyProcessor(m2ms.get(names.next())));
			}
		}
	}
	
	public String getName() {
		return name;
	}
	public String getCreateQuery() {
		return createQuery;
	}
	public String getUseQuery() {
		return useQuery;
	}
	public String getDropQuery() {
		return dropQuery;
	}
	public List<TableProcessor> getTables() {
		return tables;
	}
	public List<ManyToManyProcessor> getManyToManies() {
		return manyToManies;
	}
	public void addTable(TableProcessor tableProcessor){
		tables.add(tableProcessor);
	}
	public void addManyToMany(ManyToManyProcessor manyToManyProcessor){
		manyToManies.add(manyToManyProcessor);
	}

}
